<?php

/**
 * Role form.
 *
 * @package    maximous
 * @subpackage form
 * @author     Mina.Gerges.Wadea
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class RoleForm extends BaseRoleForm
{

    public function configure()
    {
        $this->setWidget('type', new sfWidgetFormChoice(array('choices'      => Role::$TYPE, 'expanded'     => true)));
        $roleTasksForm = new sfForm();
        if ($this->isNew())
        {
            $siteComponents = SiteComponentTable::getInstance()->findAll();
            foreach ($siteComponents as $siteComponent)
            {
                $roleTask = new RoleTasks();
                $roleTask->setSiteComponent($siteComponent);
                $roleTask->setRole($this->getObject());
                $roleTasksForm->embedForm($siteComponent->title, new RoleTasksForm($roleTask));
            }
        }
        else
        {
            $siteComponents = SiteComponentTable::getInstance()->findAll();
            foreach ($siteComponents as $siteComponent)
            {
                $roleTasksForm->embedForm($siteComponent->title, $this->getRoleTaskObject($siteComponent));
            }
        }
        $this->embedForm('RoleTask', $roleTasksForm);
        unset($this['created_at'], $this['updated_at'], $this['editable'], $this['need_category']);
    }

    public function doSave($con = null)
    {
        /*
         * any role added by user can be edit by user
         */
        $this->getObject()->setEditable(1);
        parent::doSave($con);
    }
    /**
     * check if form object content this site component so return related ToleTask object
     * else create new RoleTask object for the site component ant return it
     * @param SiteComponent $siteComponent
     * @return RoleTasks
     */
    public function getRoleTaskObject(SiteComponent $siteComponent)
    {
        foreach ($this->getObject()->getRoleTasks() as $roleTask)
        {
            if ($roleTask->getSiteComponent()->getTitle() == $siteComponent->getTitle())
            {
                return $roleTask;
            }
        }

        $roleTask = new RoleTasks();
        $roleTask->setSiteComponent($siteComponent);
        $roleTask->setRole($this->getObject());
        return $roleTask;
    }

}
